#pragma once
#include "RBTree.h"
namespace MyMap
{
	template<class K, class V>
	class map
	{
		struct MapKeyOfT
		{
			const K& operator()(const pair<K, V>& kv)
			{
				return kv.first;
			}
		};
	public:
		typedef typename RBTree<K, pair<const K, V>, MapKeyOfT>::Iterator iterator;
		typedef typename RBTree<K, pair<const K, V>, MapKeyOfT>::ConstIterator const_iterator;
		map() = default;
		map(initializer_list<pair<K, V>> il)
		{
			for (const auto& e : il)
			{
				_rbtree.Insert(e);
			}
		}
		template<class InputIterator>
		map(InputIterator first, InputIterator last)
		{
			while (first != last)
			{
				_rbtree.Insert(*first);
				++first;
			}
		}
		map(const map& x)
		{
			//_rbtree = x._rbtree;
			for (const auto& e : x)
			{
				_rbtree.Insert(e);
			}
		}
		map& operator=(const map& x)
		{
			_rbtree = x._rbtree;
			return *this;
		}
		iterator begin()
		{
			return _rbtree.Begin();
		}
		iterator end()
		{
			return _rbtree.End();
		}
		const_iterator begin() const
		{
			return _rbtree.Begin();
		}
		const_iterator end() const
		{
			return _rbtree.End();
		}
		pair<iterator, bool> insert(const pair<K, V>& kv)
		{
			return _rbtree.Insert(kv);
		}
		V& operator[](const K& key)
		{
			pair<iterator, bool> ret = insert(make_pair(key, V()));
			return ret.first->second;
		}
		iterator find(const K& key)
		{
			return _rbtree.Find(key);
		}
		void erase(const K& key)
		{
			_rbtree.Erase(key);
		}
	private:
		RBTree<K, pair<const K, V>, MapKeyOfT> _rbtree;
	};
	/*void test_map()
	{
		map<int, int> mp;
		mp.insert({ 1,10 });
		mp.insert({ 2,20 });
		mp.insert({ 3,30 });
		mp.insert({ 4,40 });
		map<int, int>::iterator it = mp.begin();
		while (it != mp.end())
		{
			cout << it->first << " " << it->second << endl;
			++it;
		}
	}*/
	void test_map()
	{
		map<string, string> dict;
		dict.insert({ "sort", "排序" });
		dict.insert({ "left", "左边" });
		dict.insert({ "right", "右边" });
		dict["left"] = "左边，剩余";
		dict["insert"] = "插入";
		dict["string"];
		map<string, string>::iterator it = dict.begin();
		while (it != dict.end())
		{
			// 不能修改first，可以修改second
			//it->first += 'x';
			it->second += 'x';
			cout << it->first << ":" << it->second << endl;
			++it;
		}
		cout << endl;
		map<string, string> mp = dict;
		mp["string"] = "string";
		mp["erase"] = "xyz";
		it = mp.begin();
		while (it != mp.end())
		{
			it->second += 'y';
			cout << it->first << ":" << it->second << endl;
			--it;
		}
		cout << endl;
		mp.erase("string");
		mp.erase("erase");
		it = mp.begin();
		while (it != mp.end())
		{
			cout << it->first << ":" << it->second << endl;
			++it;
		}
	}
}